<?php
namespace api\modules\v1\models\redPacket;

use api\modules\v1\models\group\GroupUser;
use api\modules\v1\models\user\User;
use common\models\CacheKeys;
use common\models\Functions;
use common\models\redPacket\RedPacket;
use common\models\Status;
use common\models\user\UserUnusualLog;
use Yii;
use yii\base\Exception;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class ReceiveRedPacket extends RedPacket
{
    /**
     * 领取红包
     */
    public function receiveRePacket(){
        $redis = Yii::$app->redis;

        $user = Yii::$app->getUser()->getIdentity()->toArray();
        $userId = $user['id'];
        try {
//            CacheKeys::checkFrequencyByKey("RED_PACKET_{$user['id']}",1);
//            CacheKeys::checkFrequency($userId,1);

            # 零钱封禁
            UserUnusualLog::checkUserUnusual($user['id'],Status::USER_UNUSUAL_TYPE_MONEY);

            $redPacketId = Yii::$app->request->post('id',0);
            if (!$redPacketId){
                throw new Exception('非法请求！');
            }

            $redPacketInfo = $redis->get(CacheKeys::IM_RED_PACKET.$redPacketId);
            $redPacketInfo = json_decode($redPacketInfo,true);
            if (!$redPacketInfo) {
                throw new Exception('红包不存在！');
            }

            // 个人红包需要判断接受用户身份
            if ($redPacketInfo['type'] == Status::RED_PACKET_TYPE_USER) {
                if ($redPacketInfo['to_id'] != $userId) {
                    throw new Exception('非法请求！');
                }
            } else {
                // 是否是该群成员
                $groupUserInfo = GroupUser::getOneByWhere(['group_id' => $redPacketInfo['group_id'],'user_id' => $userId]);
//                $groupUserInfo = $redis->get(CacheKeys::GROUP_USER_MESSAGE."{$redPacketInfo['group_id']}:$userId");
//                $groupUserInfo = json_decode($groupUserInfo,true);
                if (!$groupUserInfo) {
                    throw new Exception('你不是该群成员，无法领取红包！');
                }
//                Yii::info($groupUserInfo,'群成员信息');
                if ($redPacketInfo['type'] == Status::RED_PACKET_TYPE_GROUP && $groupUserInfo['is_receive_red_packet'] == Status::COMMON_RADIO_NO) {
                    throw new Exception('您无法领取该群的红包，请联系管理员！');
                }

                if ($redPacketInfo['type'] == Status::RED_PACKET_TYPE_EXCLUSIVE) {
                    // 专属红包
                    if ($redPacketInfo['to_id'] != $userId) {
                        throw new Exception('非法请求！');
                    }
                }
            }


            // 判断红包是否领取通过redis
            $lock = $redis->sadd(CacheKeys::IM_RED_PACKET_LOCK_LIST."{$redPacketInfo['id']}",$userId);
            if ($lock != 1) {
                throw new Exception('不能重复领取红包！');
            }

//            if ($redPacketInfo['status'] != Status::RED_PACKET_WAIT) {
//                throw new Exception('你来晚了！红包已领完！！');
//            }

            // 开始领取红包
            $redPacketLogInfo = $redis->lpop(CacheKeys::IM_RED_PACKET_WAIT_LIST.$redPacketId);
            $redPacketLogInfo = json_decode($redPacketLogInfo,true);
            if (!$redPacketLogInfo) {
                throw new Exception('你来晚了！红包已被领完！！');
            }

            $surplusNum = $redis->llen(CacheKeys::IM_RED_PACKET_WAIT_LIST.$redPacketId);
            $args = [
                'redPacketLog' =>  $redPacketLogInfo,
                'redPacket' =>  $redPacketInfo,
                'user' =>  $user,
                'num' =>  $surplusNum,
            ];
            // 领取红包
            Yii::$app->queue->push(new \common\queue\RedPacket($args));
//            // 发送红包脚印
//            Yii::$app->queue->push(new RedPacketMessage($args));

            return Functions::formatRestAPI(0, '领取成功');
        }  catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI($e->getCode() ? $e->getCode() : 1, $e->getMessage());
        }
    }


}
